package com.itheima.d6_synchronized_lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static java.lang.Thread.sleep;

/**
 * 目标：模拟线程安全问题。
 * lock也必须是只有一个对象
 */
public class ThreadTest {
    public static void main(String[] args) {

        myRunnable myr=new myRunnable();
        myRunnable myr1=new myRunnable();
        Thread thread1=new Thread(myr,"窗口1");
        Thread thread2=new Thread(myr1,"窗口2");
//        Thread thread3=new Thread(myr,"窗口3");

        thread1.start();
        thread2.start();
//        thread3.start();
    }
}
class myRunnable implements Runnable{
    //    private static int tickets=100;
    /**
     * 只有一个锁对象
     */
    private static Lock lock=new ReentrantLock();
    private static int tickets=100;
    @Override
    public void run() {

        while(true){
            try {
                lock.lock();
                if(tickets<=0){
                    break;
                }else {
                    tickets--;
                    System.out.println(Thread.currentThread().getName()+"正在卖票，还剩"+tickets+"张");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }

            try {
                sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        }

        }
    }


